<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="formName"
          label-width="120px"
          class="demo-ruleForm">
          <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select v-model="ruleForm.subjectID" placeholder="请选择" style="width: 400px">
              <el-option
                v-for="(item, index) in simple"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="ruleForm.catalogID" placeholder="请选择" style="width: 400px">
              <el-option
                v-for="(item, index) in directory"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="ruleForm.enterpriseID" placeholder="请选择" style="width: 400px">
              <el-option
                v-for="(item, index) in enterprise"
                :key="index"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市：" prop="province">
            <el-select
              v-model="ruleForm.province"
              placeholder="请选择"
              style="width: 198px; margin-right: 4px">
              <el-option v-for="item in provinces" :key="item" :value="item"></el-option>
            </el-select>
            <el-select v-model="ruleForm.city" placeholder="请选择" style="width: 198px">
              <el-option v-for="item in citys" :key="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="ruleForm.direction" placeholder="请选择" style="width: 400px">
              <el-option
                v-for="(item, index) in direction"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="ruleForm.questionType" @change="questionChange">
              <el-radio v-for="item in questionType" :key="item.value" :label="item.label"></el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="ruleForm.difficulty">
              <el-radio v-for="item in difficulty" :key="item.value" :label="item.label"></el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item class="quill" label="题干：" prop="question">
            <quillEditor v-model="ruleForm.question"></quillEditor>
          </el-form-item>
          <!-- 选项 -->
          <div class="mygroup">
            <el-form-item label="选项" :hidden="ruleForm.questionType === '简答'">
              <!-- 单选组 -->
              <el-radio-group v-model="radiochoice" v-show="ruleForm.questionType === '单选'">
                <div class="myradioitem" v-for="(item, index) in ruleForm.options" :key="item.code">
                  <div class="myradio">
                    <el-radio :label="item.code">{{item.code}}</el-radio>
                  </div>
                  <div class="myinput">
                    <el-input v-model="item.title" size="medium" />
                  </div>
                  <div class="myuploader" v-show="index === show[index]">
                    <el-upload
                      class="avatar-uploader"
                      action="#"
                      :show-file-list="false"
                      :http-request="($event) => {upload($event, index)}"
                    >
                      <img
                        v-if="ruleForm.options[index].imgUrl"
                        :src="ruleForm.options[index].imgUrl"
                        class="avatar-img"
                      />
                      <i v-else class="avatar-text">上传图片</i>
                    </el-upload>
                  </div>
                  <div class="myclose" v-show="index === show[index]">
                    <i class="avatar-close el-icon-circle-close" @click="closeUpload(index)"></i>
                  </div>
                </div>
              </el-radio-group>
              <!-- 多选组 -->
              <el-checkbox-group v-model="checkchoice" v-show="ruleForm.questionType === '多选'">
                <div class="myradioitem" v-for="(item, index) in ruleForm.options" :key="item.code">
                  <div class="myradio">
                    <el-checkbox :label="item.code" />
                  </div>
                  <div class="myinput">
                    <el-input v-model="item.title" size="medium" />
                  </div>
                  <div class="myuploader" v-show="index === show[index]">
                    <el-upload
                      class="avatar-uploader"
                      action="#"
                      :show-file-list="false"
                      :http-request="($event) => {upload($event, index)}"
                    >
                      <img
                        v-if="ruleForm.options[index].imgUrl"
                        :src="ruleForm.options[index].imgUrl"
                        class="avatar-img"
                      />
                      <i v-else class="avatar-text">上传图片</i>
                    </el-upload>
                  </div>
                  <div class="myclose" v-show="index === show[index]">
                    <i class="avatar-close el-icon-circle-close" @click="closeUpload(index)"></i>
                  </div>
                </div>
              </el-checkbox-group>
            </el-form-item>
            <div class="addBtn" :hidden="ruleForm.questionType === '简答'">
              <el-button type="danger" :disabled="flag" @click="addOptions">+增加选项与答案</el-button>
            </div>
          </div>
          <!-- 视频解析 -->
          <el-form-item label="视频解析" size="normal">
            <el-input v-model="ruleForm.videoURL"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item class="quill" label="答案解析" size="normal" prop="answer">
            <quillEditor  v-model="ruleForm.answer"></quillEditor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注" size="normal">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="ruleForm.remarks"></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签" size="normal">
            <el-select v-model="ruleForm.tags" value-key placeholder="请选择试题标签">
              <el-option 
                v-for="item in tagslist"
                :key="item.id"
                :label="item.tagName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item size="normal">
            <el-button type="primary" size="default" @click="submitForm(ruleForm)">确认提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 富文本样式
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
// 富文本组件
import { quillEditor } from "vue-quill-editor";
// 基础题库添加
import { add, detail } from "@/api/hmmm/questions.js";
// 城市数据导入
import { provinces, citys } from "@/api/hmmm/citys.js";
// 学科列表
import { simple } from "@/api/hmmm/subjects.js";
// 目录
import { simpleApi } from "@/api/hmmm/directorys.js";
// 标签
import { list as tagsList } from "@/api/hmmm/tags.js";
// 企业
import { list } from "@/api/hmmm/companys.js";
// 方向 难度 题型
import { direction, difficulty, questionType } from "@/api/hmmm/constants.js";
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      // 题型
      questionType,
      // 难度
      difficulty,
      // 方向
      direction,
      // 企业列表
      enterprise: [],
      // 目录
      directory: [],
      // 学科
      simple: [],
      // 试题标签列表
      tagslist: [],
      // 城市数据
      provinces: null,
      citys: null,
      province: null,
      // 表单数据
      ruleForm: {
        videoURL: "", // 视频解析
        tags: "", // 试题标签
        answer: "", // 答案解析
        remarks: "", // 题目备注
        catalogID: "", // 目录
        enterpriseID: "", // 企业
        city: "", // 地区
        subjectID: "", // 学科
        direction: "", // 方向
        province: "", // 城市
        questionType: "单选", // 题型
        difficulty: "", // 难度!!
        question: "", // 题干
        options: [
          // 选项
          { isRight: false, title: "", code: "A", imgUrl: "" },
          { isRight: false, title: "", code: "B", imgUrl: "" },
          { isRight: false, title: "", code: "C", imgUrl: "" },
          { isRight: false, title: "", code: "D", imgUrl: "" }
        ]
      },
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: "请选择学科名称", trigger: "change" }
        ],
        catalogID: [
          { required: true, message: "请选择目录", trigger: "change" }
        ],
        enterpriseID: [
          { required: true, message: "请选择企业", trigger: "change" }
        ],
        city: [{ required: true, message: "请选择城市", trigger: "change" }],
        province: [{ required: true, message: "请选择地区", trigger: "blur" }],
        direction: [
          { required: true, message: "请选择方向", trigger: "change" }
        ],
        region: [{ required: true, message: "请选择方向", trigger: "blur" }],
        questionType: [
          { required: true, message: "请选择题型", trigger: "change" }
        ],
        difficulty: [
          { required: true, message: "请选择难度", trigger: "change" }
        ],
        question: [{ required: true, message: "请输入题干", trigger: "blur" }],
        answer: [{ required: true, message: "请输入答案", trigger: "blur" }]
      },
      // 单选选项答案
      radiochoice: "",
      // 多选选项答案
      checkchoice: [],
      // 增加按钮显隐
      flag: true,
      // 控制上传组件的显隐
      show: {
        0: 0,
        1: 1,
        2: 2,
        3: 3,
        4: 4,
        5: 5,
        6: 6
      }
    };
  },
  created() {
    // 获取题目详情回填(暂时关闭)
    // this.getrouter()
    this.getsimple();
    this.getCitys();
    this.getEnterprise();
  },
  // 事件监听函数 （获取获取城市）
  watch: {
    "ruleForm.province": {
      handler(newValue) {
        this.ruleForm.city = "";
        this.citys = citys(this.ruleForm.province);
      }
    },
    "ruleForm.subjectID": {
      handler() {
        this.ruleForm.catalogue = "";
        this.ruleForm.tags = "";
        this.directory = this.getdirectory({ subjectID: this.ruleForm.subjectID });
        this.getTages({ subjectID: this.ruleForm.subjectID });
      }
    },
    // 监听单选选项的改变
    radiochoice() {
      // 所有的为false
      this.ruleForm.options.forEach(item => {
        item.isRight = false;
      });
      // 使用遍历法，不能使用索引法
      this.ruleForm.options.forEach(item => {
        if (item.code === this.radiochoice) {
          item.isRight = true;
        }
      })
    },
    // 监听多选选项的变化
    checkchoice() {
      // 所有的为false
      this.ruleForm.options.forEach(item => {
        item.isRight = false;
      });
      //遍历法
      this.ruleForm.options.forEach(item => {
        if (this.checkchoice.includes(item.code)) {
          item.isRight = true;
        }
      });
    }
  },
  methods: {
    // -----------------------------------------------------回显功能-------------------------------------
    async getrouter() {
      // 获取路由数据
      const id = this.$route.query.id
      // 判断id是否为空
      if(id === '') return
      // 获取题详情
      const { data } = await detail({id})
      // console.log(data)
      this. ruleForm = data
    },
    // -----------------------------------------------------初始数据获取----------------------------------
    // 企业
    async getEnterprise() {
      const { data } = await list();
      this.enterprise = data.items;
      // console.log('企业', this.enterprise)
    },
    // 目录
    async getdirectory({subjectID}) {
      const res = await simpleApi({subjectID});
      this.directory = res.data;
    },
    // 学科
    async getsimple() {
      const res = await simple();
      this.simple = res.data;
    },
    // 标签
    async getTages({subjectID}) {
      const { data } = await tagsList({subjectID})
      this.tagslist = data.items
    },
    getCitys() {
      this.provinces = provinces();
    },
    // ---------------------------------------------------------选项模块----------------------
    // 清空选项和答案
    clear() {
      (this.radiochoice = ""),
        (this.checkchoice = []),
        // 还原选项
        (this.ruleForm.options = [
          { isRight: false, title: "", code: "A", imgUrl: "" },
          { isRight: false, title: "", code: "B", imgUrl: "" },
          { isRight: false, title: "", code: "C", imgUrl: "" },
          { isRight: false, title: "", code: "D", imgUrl: "" }
        ]);
    },
    // 题型改变事件
    questionChange() {
      if (this.ruleForm.questionType === "单选") {
        this.flag = true;
        this.show = {
          0: 0,
          1: 1,
          2: 2,
          3: 3,
          4: 4,
          5: 5,
          6: 6
        };
        this.clear();
      } else if (this.ruleForm.questionType === "多选") {
        this.flag = false;
        this.show = {
          0: 0,
          1: 1,
          2: 2,
          3: 3,
          4: 4,
          5: 5,
          6: 6
        };
        this.clear();
      } else if (this.ruleForm.questionType === "简答") {
        this.clear();
      }
    },
    // 选择图片
    upload($event, index) {
      const a = URL.createObjectURL($event.file);
      this.ruleForm.options[index].imgUrl = a;
    },
    // 上传组件关闭
    closeUpload(index) {
      this.show[index] = "";
    },
    // 添加选项
    addOptions() {
      if (this.ruleForm.options.length >= 5) {
        this.flag = true;
        this.$message.error("最多只能有5个选项");
        return;
      }
      this.ruleForm.options.push({
        isRight: false,
        title: "",
        code: "E",
        imgUrl: ""
      });
    },
    // ------------------------------------------------------表单校验--------------------------------
    // 表单校验
    submitForm(form) {
      console.log(form);
      this.$refs.formName.validate(async valid => {
        if (valid) {
          try {
            await add(form);
            this.$router.push("./list");

            this.$message.success("试题录入成功");
          } catch (error) {
            this.$message.error(error);
          }

          // alert('submit!')
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 表单重置方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addForm() {}
  }
};
</script>

<style lang="scss" scoped>
.mygroup {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  .myradioitem {
    width: 300px;
    min-height: 100px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .myinput {
      margin-left: 15px;
    }
    .myuploader {
      margin-left: 15px;
      width: 100px;
      height: 60px;
      // background-color: pink;
      ::v-deep .avatar-uploader .el-upload {
        width: 100%;
        height: 100%;
        // background-color: pink;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-text {
        font-size: 12px;
        color: #8c939d;
        line-height: 60px;
        text-align: center;
      }
      .avatar-img {
        width: 100px;
        height: 60px;
        display: block;
      }
    }
    .myclose {
      font-size: 20px;
      color: #8c939d;
      cursor: pointer;
      margin-top: -48px;
      margin-left: -8px;
    }
  }
  .addBtn {
    margin-left: 120px;
  }
}
::v-deep .ql-editor {
  min-height: 100px;
}
</style>
